﻿using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NewLife;
using PMS.WebApi.Models;
using PMS.WebApi.Utils;

namespace PMS.WebApi.Attributes
{
    public class ApiJwtActionFilter : ActionFilterAttribute
    {
        readonly string[] _role;
        /// <summary>
        /// 用户权限校验
        /// </summary>
        /// <param name="role">可以通过的权限</param>
        public ApiJwtActionFilter(params string[] role)
        {
            _role = role;
        }

        public override async void OnActionExecuting(ActionExecutingContext actionContext)
        {
            //url获取token
            var request = actionContext.HttpContext.Request;
            //var content = request.Properties["MS_HttpContext"] as HttpContext;
            //var ip = actionContext.HttpContext.Connection.RemoteIpAddress.ToString();
            var ip = actionContext.HttpContext.Request.Headers["X-Real-IP"].ToString();
            var token = actionContext.HttpContext.Request.Headers["Access-Token"].ToString();

            try
            {
                if (ip.IsNullOrEmpty())
                    ip = actionContext.HttpContext.Connection.RemoteIpAddress.ToString();

                #region Access-Token 校验
                //var authHeader = from t in request.Headers where t.Key == "access-token" select t.Value.FirstOrDefault();
                //if (authHeader != null)
                //{
                //string _token = authHeader.FirstOrDefault();
                var jwtObj = JwtHelper.GetJwtDecode(token);
                if (jwtObj == null)
                    throw new JWT.Exceptions.TokenExpiredException("Invalid access token!");

                #region Token有效期校验
                //object expireTime = null;
                //jwtObj.TryGetValue("expire_time", out expireTime);
                //if (expireTime == null || expireTime.ToDateTime() < DateTime.Now)
                //{
                //    var response = actionContext.HttpContext.Response;
                //    response.StatusCode = (int)HttpStatusCode.Unauthorized;
                //    var content = new ResultMsg
                //    {
                //        code = 40002,
                //        success = false,
                //        message = "The token has expired. Please use your account again to obtain the token before accessing it again!"
                //    };
                //    await response.WriteAsJsonAsync(content);
                //    //response.WriteAsync(content.ToJson(), Encoding.UTF8);
                //    //加了这句就不再走后面的Action
                //    actionContext.Result = new JsonResult(content);
                //    return;
                //}
                #endregion
                //}
                #endregion

                base.OnActionExecuting(actionContext);
            }
            catch (JWT.Exceptions.TokenExpiredException ex)
            {
                var response = actionContext.HttpContext.Response;
                response.StatusCode = (int)HttpStatusCode.Unauthorized;
                var content = new ResultMsg
                {
                    code = 40001,
                    success = false,
                    message = "The token has expired. Please use your account again to obtain the token before accessing it again!"
                };
                //await response.WriteAsJsonAsync(content);
                //response.WriteAsync(content.ToJson(), Encoding.UTF8);
                //加了这句就不再走后面的Action
                actionContext.Result = new JsonResult(content);
            }
            catch (Exception ex)
            {
                var response = actionContext.HttpContext.Response;
                response.StatusCode = (int)HttpStatusCode.Forbidden;
                var content = new ResultMsg
                {
                    success = false,
                    message = "服务端拒绝访问：您没有权限或者网络异常！Access denied by the server: You do not have permission or there is a network abnormality!"
                };
                await response.WriteAsJsonAsync(content);
                //response.WriteAsync(content.ToJson(), Encoding.UTF8);
                //加了这句就不再走后面的Action
                actionContext.Result = new JsonResult(content);
            }
        }
    }
}
